package net.hn.hnms.biz.common.activiti.builder;

import net.hn.hnms.biz.common.activiti.params.ProcessQueryParam;
import net.hn.hnms.biz.common.activiti.result.ProcessHistoryResult;
import net.hn.hnms.biz.common.activiti.service.ProcessApiService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;

/**
 * Created on 2022/8/5.
 *
 * @author ly
 * @desc: 流程实例信息查询器
 */
public class ProcessQuery {
    /**
     * 运行中的流程实例id
     */
    private String processInstanceId;

    /**
     * 业务编码
     */
    private String businessKey;
    private final ProcessQueryParam processQueryParam = new ProcessQueryParam();
    private ProcessApiService processApiService;

    private ProcessQuery() {
    }

    public ProcessQuery(ProcessApiService processApiService) {
        this.processApiService = processApiService;
    }

    public ProcessQuery processInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
        processQueryParam.setProcessInstanceId(this.processInstanceId);
        return this;
    }

    public ProcessQuery businessKey(String businessKey) {
        this.businessKey = businessKey;
        processQueryParam.setBusinessKey(this.businessKey);
        return this;
    }

    /**
     * 获得流程图输入流
     * @return  InputStream 流程图输入流
     */
    public InputStream processImage() {
        return processApiService.getActivityProcessImage(processQueryParam);
    }

    /**
     * 获得Base64格式的流程图
     * @return Base64格式的流程图
     */
    public String processImageBase64() {
        try (InputStream imageStream = processImage()) {
            byte[] bytes = IOUtils.toByteArray(imageStream);
            String encoded = Base64.getEncoder().encodeToString(bytes);
            return "data:image/png;base64," + encoded;
        } catch (IOException e) {
            throw new HuaNengException(Constants.FAIL,"获得流程图片BASE64失败");
        }
    }

    /**
     * 获得运行中的流程执行历史记录
     * @return List<ProcessHistoryResult>
     */
    public List<ProcessHistoryResult> processHistoryTracking() {
        return processApiService.processTrackingList(processQueryParam);
    }

}
